#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib,urllib2,httplib,json
from xml.dom.minidom import parseString


############################################################################
    
def urlopen(url):
    res=urllib2.urlopen(url)
    temp=res.read()
    res.close()
    return temp

############################################################################

class GoogleService(object):
    def __init__(self):
        self.url="https://ajax.googleapis.com/ajax/services/language/"
        
class MicrosoftService(object):
    """
    参考文档：http://www.microsofttranslator.com/dev/
    """
    def __init__(self):
        self.key="EcK/bqI8NTN64/iNw3YjOkMNhGfXHnjl+IUaSFFqpPI="
        
class BaiduService(object):
    """
    参考文档：http://developer.baidu.com/wiki/index.php
    """
    def __init__(self):
        self.client_id="09gYErz7HGnqwE34PhXB9jnP"
        

############################################################################

"""
语言检测 --------------------------------------------------------------------
""" 

class GoogleLangDetect(GoogleService):
    """
    Google 该服务已停用
    """
    def request(self,text):
        params = urllib.urlencode({"v":"1.0","q":text})
        url="https://ajax.googleapis.com/ajax/services/language/detect?"+params
        data=urlopen(url)
        obj=json.loads(data)
        return obj[u'responseData'][u'language']
        
class MsLangDetect(MicrosoftService):
    
    def __init__(self):
        super(MsLangDetect,self).__init__()
    
    def request(self,text):
        """
        Http 返回数据格式：<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">en</string>
        """
        params = urllib.urlencode({"AppId":self.appid,"text":text})
        url= "http://api.microsofttranslator.com/V2/Http.svc/Detect?"+params
        data = urlopen(url)
        dom=parseString(data)
        return  dom.documentElement.firstChild.data
    
class BaiduDetect(BaiduService):
    """
    Microsoft 翻译
    """
    
    def request(self,text):
        params = urllib.urlencode({"client_id":self.client_id,"q":text,"from":"auto","to":"auto"})
        url="http://openapi.baidu.com/public/2.0/bmt/translate?"+params
        data=urlopen(url)
        obj=json.loads(data)
        return obj['from']
        
############################################################################ 

"""
翻译 -----------------------------------------------------------------------
"""        
class GoogleTranslate(GoogleService):
    """
    Google 翻译：该服务已停用
    """
    def __init__(self):
        super(GoogleTranslate,self).__init__()
        self.url=self.url+"translate?"
    
    def request(self,langpair,text):
        params = urllib.urlencode({"v":"1.0","langpair":langpair,"q":text})
        url= self.url+params
        res=urllib2.urlopen(url)
        temp=res.read()
        res.close()
        obj=json.loads(temp)
        return obj[u'responseData'][u'translatedText']
        
    def toEnglisgh(self,text):
        self.request("zh-CN|en",text)
        
    def toChinese(self,text):
        self.request("en|zh-CN",text)        
        
class MsTranslate(MicrosoftService):
    """
    Microsoft 翻译
    """
    
    def __init__(self):
        super(MsTranslate,self).__init__()
    
    def request(self,text,p_from,p_to):
        """
        返回数据格式：<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">en</string>
        """
        params = urllib.urlencode({"appid":self.appid,"text":text,"from":p_from,"to":p_to})
        url= "http://api.microsofttranslator.com/V2/Http.svc/Translate?"+params
        data=urlopen(url)
        dom=parseString(data)
        tr=dom.documentElement.firstChild.data
        #可能需要对字符进行编码
        if(isinstance(tr,unicode)):
            tr=tr.encode("utf-8")
        return tr
        
    def toEnglish(self,text):
        return self.request(text,"zh-CN","en")
        
    def toChinese(self,text):
        return self.request(text,"en","zh-CN")
        
        
class BaiduTranslate(BaiduService):
    """
    Baidu 翻译
    """
    
    def request(self,text,p_from,p_to):
        """
        返回数据格式：{"from":"en","to":"zh","trans_result":[{"src":"cup","dst":"\u676f"}]}
        """
        params = urllib.urlencode({"client_id":self.client_id,"q":text,"from":p_from,"to":p_to})
        url="http://openapi.baidu.com/public/2.0/bmt/translate?"+params
        data=urlopen(url)
        obj=json.loads(data)
        return obj['trans_result'][0]['dst']
        
    def toEnglish(self,text):
        return self.request(text,"zh","en")
        
    def toChinese(self,text):
        return self.request(text,"en","zh")
            

############################################################################
"""
TTS ------------------------------------------------------------------------
"""
        
class GoogleTTS(GoogleService):
    def __init__(self):
        super(GoogleTTS,self).__init__()
        self.url="http://translate.google.cn/translate_tts?"
    
    def request(self,tl,text):
        params = urllib.urlencode({"ie":"utf-8","v":"1.0","tl":tl,"q":text})
        url= self.url+params
        print url
        req=urllib2.Request(url)
        req.add_header('Host','translate.google.cn')
        req.add_header('Connection','keep-alive')
        req.add_header('Cache-Control','max-age=0')
        req.add_header('User-Agent','Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1')
        req.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
        req.add_header('Accept-Encoding','gzip,deflate,sdch')
        req.add_header('Accept-Language','zh-CN,zh;q=0.8')
        req.add_header('Accept-Charset','GBK,utf-8;q=0.7,*;q=0.3')
        res=urllib2.urlopen(req)
        data=res.read()
        res.close()
        return data
    
class MsTTS(MicrosoftService):
    def __init__(self):
        super(MsTTS,self).__init__()
    
    def request(self,lang,text):         
        params = urllib.urlencode({"language":lang,"format":"audio/mp3","options":"MaxQuality","AppId":self.appid,"text":text})
        url= "http://api.microsofttranslator.com/V2/Http.svc/Speak?"+params
        data = urlopen(url)
        return data
    
class BaiduTTS(BaiduService):
    def request(self,text):
        url="http://bs.baidu.com/dictmid2/en/"+text+".mp3"
        data = urlopen(url)
        return data
    
 
 
############################################################################
"""
图片搜索 ------------------------------------------------------------------------
"""
class GoogleImageSearch(GoogleService):
    def __init__(self,text):
        super(GoogleImageSearch,self).__init__()
        self.text=text
        self.start=0
    
    def request(self):
        params = urllib.urlencode({"v":"1.0","start":self.start,"q":self.text})
        url= "https://ajax.googleapis.com/ajax/services/search/images?"+params
        self.start=self.start+4
        data=urlopen(url)
        obj=json.loads(data)
        results=obj[u'responseData'][u'results']
        return [item[u'url'] for item in results]
        
class MsImageSearch(MicrosoftService):
    
    def __init__(self,text):
        super(MsImageSearch,self).__init__()
        self.text="'%s'" % text
        self.skip=0

    def request(self):
        url = "https://api.datamarket.azure.com/Bing/Search/Image?$format=json&$top=10&Market=%27zh-CN%27"
        url = url + "&$skip=" + str(self.skip) + "&Query=" + urllib.quote(self.text)
        self.skip+=10

        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        password_mgr.add_password(None, url,"wlnh_2004",self.key)
        
        handler = urllib2.HTTPBasicAuthHandler(password_mgr)
        opener = urllib2.build_opener(handler)
        urllib2.install_opener(opener)
        data = urllib2.urlopen(url).read()
        obj=json.loads(data)
        li=[]
        try:
            results=obj[u'd'][u'results']
            li=[item[u'MediaUrl'] for item in results]
        except KeyError,e:
            print u"JSON 格式错误：",data,e
        return li
        
if __name__=='__main__':
    
    gld=MsImageSearch("apple")
    print gld.request()
    
    
    
    